#include <types.h>
#include <vfs/mount.h>
#include <vfs/file.h>
#include <vfs/vfs.h>
#include <klibc/string.h>
#include <klibc/stdio.h>
#include <klibc/malloc.h>


/* mount a filesystem */
int 
vfs_mount(char *device, char *path, char *fs, char *flags)
{
	/* check the path */
	if(strcmp(path, "/") != 0)
	{
		dir_t *d = vfs_opendir(path);
		if(d == NULL)
			return -1;
	}
	
	/* check if the path is allocated as a different mp */
	if(strcmp(path, mountpoint_get_from_path(path)->path) == 0)
		return -1;
	
	/* check the device */
	
	
	
	/* check the fs */
	mount_point_t *mp = (mount_point_t *) malloc(sizeof(mount_point_t));
	
	if(strcmp(fs, "tmpfs") == 0)
	{
		/* call mount function */
		
		mp->driver = NULL;
	}
	else
	{
		free(mp);
		mp = NULL;
		
		return -1;
	}
	
	
	/* add it to the list */
	strcpy(mp->path, path);
	
	mp->next = mountlist;
	mountlist = mp; 
	
	return 0;
}



/* get the i mountpoint */
mount_point_t *
mountpoint_iget(int i)
{
	#ifdef NO_VFS
		return (mount_point_t *) NULL;
	#endif
	
	mount_point_t *d = mountlist;
	int j = 0;
	
	while(d != NULL)
	{
		if(i == j)
			return d;
			
		j++;
		d = d->next;
	}
	return NULL;	
}


/* umount a filesystem (partially completed) */
int 
vfs_umount(char *device_or_path)
{
	mount_point_t *m = mountlist;
	mount_point_t *p = NULL;
	
	while(m != NULL)
	{
		if(	(strcmp(m->path, device_or_path) == 0) || 
			(strcmp((m->driver)->name, device_or_path) == 0))
		{
			/* call umount function, from the fs struct */
			
			/* free the mountpoint */
			if(p != NULL)
			{
				p->next = m->next;
				free(m);
			}
			else
				mountlist = m->next;
				
			return 0;
		}
		
		p = m;
		m = m->next;
	}
	
	return -1;	
}


















/* return mp from path */
mount_point_t *mountpoint_get_from_path(char *path)
{
	int len = 0;
	mount_point_t *mp = mountlist;
	mount_point_t *best = NULL;
	
	while(mp != NULL)
	{
		if((strncmp(mp->path, path, strlen(mp->path)) == 0) && (strlen(mp->path) > len))
		{
			best = mp;
			len = strlen(best->path);
		}
		
		mp = mp->next;
	}
	return best;
}
